package org.buptsse.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.buptsse.entity.Circle;
import org.buptsse.entity.Comment;
import org.buptsse.entity.Friend;
import org.buptsse.entity.Messagebox;
import org.buptsse.entity.Post;
import org.buptsse.entity.Track;
import org.buptsse.entity.Tutelage;
import org.buptsse.entity.User;
import org.json.JSONArray;
import org.json.JSONObject;

public class Action {

	private static final int MAXSIZE = 1024 * 10 * 1024;
	private static String savePath = null;
	private static final String serverIp = "59.64.164.209";
	private static final int downLoadServerPort = 9999;
	private static final String URL_BASE="http://59.64.164.221:8080/Zhiliao/";
	private long length;
	private String fileType;



	public String uploadFile(String filePath, int postId, String serverIp,
			int serverPort) {
		int point = filePath.lastIndexOf('.');
		this.setFileType(filePath.substring(point + 1, filePath.length()));
		if (this.getFileType().equals("jpg")
				|| this.getFileType().equals("png")
				|| this.getFileType().equals("gif")
				|| this.getFileType().equals("mp3")
				|| this.getFileType().equals("arm")
				|| this.getFileType().equals("png")
				|| this.getFileType().equals("jpeg")) {
			try {
				File file = new File(filePath);

				Socket s = new Socket(InetAddress.getByName(serverIp),
						serverPort);
				InputStream input = s.getInputStream();
				OutputStream output = s.getOutputStream();
				DataInputStream dis = new DataInputStream(input);
				DataOutputStream dos = new DataOutputStream(output);
				FileInputStream in = new FileInputStream(filePath);
				this.setLength(file.length());
				JSONObject obj = new JSONObject();
				obj.put("filelength", this.getLength());
				obj.put("postid", postId);
				obj.put("filetype", this.getFileType());

				dos.writeUTF(obj.toString());
				dos.flush();
				String infor = dis.readUTF();
				if (infor.equals("ready")) {
					dos.writeUTF("start");
					dos.flush();
					byte[] buffer = new byte[2048];
					int c;
					while ((c = in.read(buffer)) != -1) {
						output.write(buffer, 0, c);
						output.flush();
					}
					String response = dis.readUTF();
					if (response.equals("finish"))
						return "success";
					dis.close();
					dos.close();
					s.close();
				} else
					return "fail";
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else
			return "fail";
		return "success";
	}

	
	public String downLoad(String  path,String savePath,String fileName)
	{
	  
	  System.out.println("filaName:"+fileName);
	  try{
	   URL url=new URL(path);
	   HttpURLConnection conn=(HttpURLConnection)url.openConnection();
	   conn.setConnectTimeout(5*1000);
	   conn.setRequestMethod("GET");
	   
	   InputStream input=conn.getInputStream();
	   if(conn.getResponseCode()==HttpURLConnection.HTTP_OK)
	   {
		   System.out.println("’˝»∑ªÒ»°µΩ∑˛ŒÒ∆˜µƒ¥¶¿Ì ˝æ›");
		   int c;
		   byte[] buffer=new byte[2048];
		   File file=new File(savePath);
		   if(!file.exists())file.mkdir();
		   File temp=new File(savePath,fileName);
		   if(!file.exists())temp.createNewFile();
		   FileOutputStream fos=new FileOutputStream(savePath+"\\"+fileName);
		   System.out.println("fos:"+savePath+"\\"+fileName);
		   while((c=input.read(buffer))!=-1)
		   {
			   fos.write(buffer, 0, c);
			   fos.flush();
		   }
		   fos.close();
	   }
	   
	  }catch(Exception e)
	  {
		  e.printStackTrace();
	  }
		return "success";
	}

	// 发私信
	public boolean sendMessage(String Url, int FromId, int ToId, String content) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject obj = new JSONObject();
		try {
			obj.put("toid", ToId);
			obj.put("fromid", FromId);
			obj.put("content", content);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				if(null!=responseStr&&"success".equals(responseStr))
					return true;
				else
					return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// 获取当个对象的信息，返回该对象的粉丝数，关注数，微博发表总数，与我的互粉关系，昵称,UserId是我的昵称，ObjectId是查找对象的Id
	public User FetchIndividualPersonInfor(String Url, int ObjectId, int UserId) {

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		User user = new User();
		JSONObject obj = new JSONObject();
		try {
			obj.put("userid", UserId);
			obj.put("objectid", ObjectId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");

				user.setId(object.getInt("userid"));
				user.setName(object.getString("name"));
				user.setFan(object.getInt("fan"));
				user.setFollow(object.getInt("follow"));
				user.setPostAmount(object.getInt("postamount"));
				user.setIsFollow(object.getBoolean("isfollow"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	// 互粉hufen为true，则双方都互相关注了，如果为false，则仅仅是我关注了别人
	public List<Friend> fetchFollowInfor(String Url, int UserId) {
		List<Friend> list = new ArrayList<Friend>();
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject obj = new JSONObject();
		try {
			obj.put("userid", UserId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("followinfor");
				try {
					JSONObject tem = null;
					JSONArray array = object.getJSONArray("follow");
					for (int i = 0; i < array.length(); i++) {
						tem = array.getJSONObject(i);
						Friend friend = new Friend();
						friend.setUid(tem.getInt("id"));

						friend.setUname(tem.getString("name"));
						friend.setHufen(tem.getBoolean("flag"));
						friend.setPostamount(tem.getInt("postamount"));
						list.add(friend);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/*
	 * public String fileUpload(String url, int postId, String path) {
	 * .out.println("path:" + path); final int MAXSIZE = 1024 * 1024 * 10;
	 * try { File file = new File(path); if (file.length() > MAXSIZE) return
	 * "文件大小不能超过10MB，上传失败！"; int lastPoint = path.lastIndexOf("."); String
	 * fileExt = path.substring(lastPoint, path.length());
	 * .out.println("fileExt:" + fileExt); FileInputStream in = new
	 * FileInputStream(path); byte buffer[] = new byte[MAXSIZE]; int c; while
	 * ((c = in.read(buffer)) != -1) { } StringBuilder builder = new
	 * StringBuilder(); for (int i = 0; i < buffer.length; i++) { //
	 * .out.println(buffer[i]); builder.append(buffer[i]); } HttpClient
	 * client = new DefaultHttpClient(); HttpPost post = new HttpPost(url);
	 * List<NameValuePair> pair = new ArrayList<NameValuePair>(); JSONObject obj
	 * = new JSONObject(); obj.put("buffer", builder.toString());
	 * obj.put("postid", postId); obj.put("fileext", fileExt); pair.add(new
	 * BasicNameValuePair("json", obj.toString())); post.setEntity(new
	 * UrlEncodedFormEntity(pair, HTTP.UTF_8)); HttpResponse response =
	 * client.execute(post); if (response.getStatusLine().getStatusCode() ==
	 * 200) { .out
	 * .println("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
	 * HttpEntity entity = response.getEntity(); String responseStr =
	 * EntityUtils.toString(entity); new
	 * AlertDialog.Builder(this).setMessage(responseStr).create() .show(); } }
	 * catch (Exception e) { e.printStackTrace(); } return "success"; }
	 */

	// 删除被监护的信息，TutelageId是监护人的id，Userid是监护人自己的id
	public boolean DeleteTutelage(String Url, int TutelageId, int UserId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("tutelageid", TutelageId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				if(null!=responseStr&&"success".equals(responseStr))
					return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// Url:UserName是转发人的名字，UserId是转发人的Id,PostId是转发的微博的主键
	public void Repost(String Url, int UserId, String UserName, int PostId,
			String Content, int CircleId, String CircleName, double longitude,
			double latitude) {
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("content", Content);
			obj.put("username", UserName);
			obj.put("postid", PostId);
			obj.put("circlename", CircleName);
			obj.put("circleid", CircleId);
			obj.put("messagetype", 1);
			obj.put("longitude", longitude);
			obj.put("latitude", latitude);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// Url:/getFanInfor 返回粉丝的昵称，粉丝的趣闻条数，粉丝的id号
	// 供用户获取自己粉丝的信息，userid是用户自己的id号
	public List<User> GetFanInfor(String Url, int UserId, int minId) {
		List<User> list = new ArrayList<User>();
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("minid", minId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONArray array = object.getJSONArray("fan");
				for (int i = 0; i < array.length(); i++) {
					User user = new User();
					obj = array.getJSONObject(i);
					user.setId(obj.getInt("id"));
					user.setPostAmount(obj.getInt("postamount"));
					user.setName(obj.getString("name"));
					user.setIsFollow(obj.getBoolean("flag"));
					user.setRelationId(obj.getInt("relationid"));
					list.add(user);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// Url:/deleteFan
	// 供用户删除恶意粉丝的函数，userid是用户的主id，fanid是粉丝的id
	public void DeleteFan(String Url, int UserId, int FanId) {

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("fanid", FanId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Url:/getTrack
	// 供用户获取监护对象或者自己的在一定时间内的活动轨迹，HostId是监护对象的主id，begin是轨迹的开始时间段(要求时间是字符串，符合20110101121212这样的格式)
	public List<Track> GetTrack(String Url, int HostId, String Begin) {
		List<Track> list = new ArrayList<Track>();

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("hostid", HostId);
			obj.put("begin", Begin);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONArray array = object.getJSONArray("track");
				for (int i = 0; i < array.length(); i++) {
					Track track = new Track();
					obj = array.getJSONObject(i);
					track.setUserId(obj.getInt("hostid"));
					track.setLongitude(obj.getDouble("longitude"));
					track.setLatitude(obj.getDouble("latitude"));
					track.setTime(obj.getString("time"));
					list.add(track);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// Url:/storeTrack
	// 供用户记录自己的轨迹用，上传用户的经纬度，,userid是用户的主id
	public void StoreTrack(String Url, int UserId, double Longitude,
			double Latitude) {

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("longitude", Longitude);
			obj.put("latitude", Latitude);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Url:/dealTutelageApply
	// 供用户处理监护信息的函数，userid是用户的主id，hostid是申请监护用户的人的id，username是用户自己的名字，allow是允许或不同意
	public boolean DealTutelageApply(String Url, int UserId, int HostId,
			String UserName, boolean Allow) {
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("hostid", HostId);
			obj.put("name", UserName);
			obj.put("allow", Allow);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString((entity), "utf8");
				if(null!=responseStr&&"success".equals(responseStr))
					return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// Url:/applyTutelage
	// 供用户申请监护他人时调用的函数，userid是用户自己的id，UserName是我的名字，hostid是监护对象的id号
	public void ApplyTutelage(String Url, int UserId, String userName,
			int HostId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("hostid", HostId);
			obj.put("username", userName);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString((entity), "utf-8");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	// Url:/getFollowTutelageObject||getFanTutelageObject
	// 供用户获取监护对象的信息，传入的是用户自己的id号，返回监护对象的id号和名字
	public List<Tutelage> GetTutelageObject(String Url, int UserId,int minId) {
		List<Tutelage> list = new ArrayList<Tutelage>();

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("minid",minId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity,"utf-8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONArray array = object.getJSONArray("tutelage");
				for (int i = 0; i < array.length(); i++) {
					Tutelage tu = new Tutelage();
					obj = array.getJSONObject(i);
					tu.setObjectId(obj.getInt("objectid"));
					System.out.println("objectid:" + tu.getObjectId());
					tu.setObjectName(obj.getString("objectname"));
					System.out.println("objectname:" + tu.getObjectName());
					tu.setFlag(obj.getInt("flag"));
					tu.setImage(obj.getString("image"));
					list.add(tu);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}


	public List<Friend> FetchFollowInfor(String Url, int uid) {

		List<Friend> list = new ArrayList<Friend>();

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", uid);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("followinfor");
				JSONObject tem = null;
				JSONArray array = object.getJSONArray("follow");
				for (int i = 0; i < array.length(); i++) {
					tem = array.getJSONObject(i);
					Friend temp = new Friend();
					temp.setUname(tem.getString("name"));
					temp.setUid(tem.getInt("id"));
					temp.setHufen(tem.getBoolean("flag"));
					temp.setPostamount(tem.getInt("postamount"));
					list.add(temp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;

	}

	// Url:/fetchFollowPost
	// 供用户获取关注对象的最近更新信息，需要传入用户的主id
	// flag -1刷新 0 第一次 1 更多
	public List<Post> FetchFollowPost(String Url, int UserId, int minPostId,
			int flag) {
		List<Post> list = new ArrayList<Post>();

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("minpostid", minPostId);
			obj.put("flag", flag);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONArray array = object.getJSONArray("post");
				for (int i = 0; i < array.length(); i++) {
					Post post = new Post();
					obj = array.optJSONObject(i);
					post.setMessageType(obj.getInt("messagetype"));
					if (post.getMessageType() == 1) {// 1为转发，0为原创微博
						post.setHostId(obj.getInt("hostid"));// 存储被转发人的id
						post.setOriginalPostId(obj.getInt("originalpostid"));
						post.setOriginalPostContent(obj
								.getString("originalpostcontent"));
						post.setOriginalPostContent(obj
								.getString("originalusername"));
						post.setOriginalImage(obj.getString("originalimage"));
						post.setOriginalLink(obj.getString("originallink"));
						if (IsPicture(post.getOriginalLink()))
							post.setOriginalDisplay(true);
						else
							post.setOriginalDisplay(false);
					}
					post.setLink(obj.getString("link"));
					if (IsPicture(post.getLink()))
						post.setDisplay(true);
					else
						post.setDisplay(false);
					post.setPostId(obj.getInt("id"));
					post.setUserId(obj.getInt("userid"));
					post.setImage(obj.getString("image"));
					post.setPostContent(obj.getString("content"));
					post.setPostTime(obj.getString("time"));
					post.setUsername(obj.getString("username"));
					post.setRepostAmount(obj.getInt("repost"));
					post.setCommentsAmount(obj.getInt("commentamount"));
					list.add(post);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// Url:/deleteFollow
	// 供用户删除关注对象用，传入的是用户的id和将要删除的关注对象的id
	public boolean DeleteFollow(String Url, int UserId, int FollowId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("followid", FollowId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				if (null != responseStr && "success".equals(responseStr))
					return true;
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// Url:/addFollow
	// 供用户添加关注对象用，传入的是用户自身的id和关注对象的id号,还有用户自己的名字
	public boolean AddFollow(String Url, int UserId, int FollowId,
			String UserName) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("followid", FollowId);
			obj.put("username", UserName);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				if (null != responseStr && "success".equals(responseStr)) {
					return true;
				}
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// Url:/getPersonalInfor
	// 用户获取个人资料的函数，传入的是用户个人的主键,返回的是user对象，user中的某些属性被填充，如下
	public User GetPersonalInfor(String Url, int UserId) {
		User user = new User();
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				user.setAge(object.getInt("age"));
				user.setBirthday(object.getString("birthday"));
				user.setHometown(object.getString("hometown"));
				user.setSex(object.getString("sex"));
				user.setSecureScope(object.getInt("securescope"));
				user.setName(object.getString("name"));

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	// Url:/setPersonalInfor
	// 个人资料设置，每次设置时先获取数据库中个人的资料设置情况，用户在修改了自己的资料后调用该函数
	public void SetPersonalInfor(String Url, int UserId, double SecureScope,
			String Name, int Age, String BirthDay, String Password, String Sex,
			String Hometown) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("name", Name);
			obj.put("age", Age);
			obj.put("birthday", BirthDay);
			obj.put("password", Password);
			obj.put("sex", Sex);
			obj.put("scope", SecureScope);
			obj.put("hometown", Hometown);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Url:/getSurroundPost
	// 获取在该经纬度下其他用户在此处的标记信息，标记信息默认存为circleid为-2的圈子，scope为设定半径
	public List<Post> GetSurroundPost(String Url, double Longitude,
			double Latitude, int scope, int minPostId) {
		List<Post> list = new ArrayList<Post>();

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("longitude", Longitude);
			obj.put("latitude", Latitude);
			obj.put("scope", scope);
			obj.put("minpostid", minPostId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONArray array = object.getJSONArray("surroundpost");
				for (int i = 0; i < array.length(); i++) {
					Post post = new Post();
					obj = array.optJSONObject(i);
					post.setPostId(obj.getInt("postid"));
					post.setPostContent(obj.getString("content"));
					post.setPostTime(obj.getString("time"));
					post.setUserId(obj.getInt("userid"));
					post.setLink(obj.getString("link"));
					if (IsPicture(post.getLink()))
						post.setDisplay(true);
					else
						post.setDisplay(false);
					post.setLongitude(obj.getDouble("longitude"));
					post.setLatitude(obj.getDouble("longitude"));
					post.setDistance(obj.getDouble("distance"));
					list.add(post);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public boolean IsPicture(String url) {

		int point = url.lastIndexOf('.');
		if (point == -1)
			return false;
		String pofix = url.substring(point + 1, url.length());
		if (pofix.equals("jpg") || pofix.equals("gif") || pofix.equals("jpeg")
				|| pofix.equals("png")) {
			return true;
		} else {
			return false;
		}
	}

	// Url:/getMyPost
	// 获取本人发表的所有微博，这种获取方式不对，后期考虑更改
	public List<Post> GetMyPost(String Url, int UserId, int minPostId, int flag) {
		List<Post> list = new ArrayList<Post>();

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("minpostid", minPostId);
			obj.put("flag", flag);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString((entity), "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("array");
				JSONArray array = object.getJSONArray("mypost");
				for (int i = 0; i < array.length(); i++) {
					Post post = new Post();
					obj = array.getJSONObject(i);
					post.setMessageType(obj.getInt("messagetype"));
					if (post.getMessageType() == 1) {// 1为转发，0为原创微博
						post.setHostId(obj.getInt("hostid"));// 存储被转发人的id
						post.setOriginalPostId(obj.getInt("originalpostid"));
						post.setHostId(obj.getInt("hostid"));
						post.setOriginalPostContent(obj
								.getString("originalpostcontent"));
						post.setOriginalUsername(obj
								.getString("originalusername"));
						post.setOriginalImage(obj.getString("originalimage"));
						post.setOriginalLink(obj.getString("originallink"));
						if (IsPicture(post.getOriginalLink()))
							post.setOriginalDisplay(true);
						else
							post.setOriginalDisplay(false);
					}
					post.setLink(obj.getString("link"));
					if (IsPicture(post.getLink()))
						post.setDisplay(true);
					else
						post.setDisplay(false);
					post.setPostId(obj.getInt("postid"));
					// .out.println("postid:" + post.getPostId());
					post.setPostContent(obj.getString("content"));
					// .out.println("content:" + post.getPostContent());
					post.setPostTime(obj.getString("time"));
					// .out.println("time:" + post.getPostTime());
					post.setRepostAmount(obj.getInt("repost"));
					// .out.println("repost:" + post.getRepostAmount());
					post.setCommentsAmount(obj.getInt("commentamount"));
					post.setCircleName(obj.getString("circlename"));
					post.setImage(obj.getString("link"));
					// .out.println("circlename:" + post.getCircleName());
					// .out.println("commentamount:"
					// + post.getCommentsAmount());
					post.setCircleId(obj.getInt("circleid"));
					list.add(post);
				}
			} else {
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// DownLoadPicture(list);
		return list;// 如果检查到OriginalLink或者Link中是none字符串，则表示无图像和资源链接，不必显示在界面上
	}

	// Url:/fetchComment
	// 供用户获取某条微博的对应的评论，返回评论人id，评论人姓名，时间，和言论，比较客户端的主人id与评论人id，相同则增加删除评论的按钮
	public List<Comment> FetchComment(String Url, int PostId) {
		List<Comment> list = new ArrayList<Comment>();
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("postid", PostId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {

				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString((entity), "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONArray array = object.getJSONArray("comment");
				for (int i = 0; i < array.length(); i++) {
					Comment comment = new Comment();
					obj = array.getJSONObject(i);
					comment.setComment(obj.getString("comment"));
					comment.setCommentId(obj.getInt("commentid"));
					comment.setPostId(obj.getInt("postid"));
					comment.setCommentPeopleId(obj.getInt("commentpeopleid"));
					comment.setCommentPeopleName(obj
							.getString("commentpeoplename"));
					comment.setTime(obj.getString("commenttime"));
					list.add(comment);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// Url:/deleteComment
	// 当用户是评论的微博的主人或者是该评论的持有者时，可以删除该评论，在此需要客户端执行严格的检验以标记删除按钮
	public void DeleteComment(String Url, int CommentId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("commentid", CommentId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				String responseStr = EntityUtils.toString(response.getEntity(),
						"utf8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Url:/addComment
	// 供用户评论他人的微博用，PostId是评论的微博的id，Userid是微博的发表人的Id，CommentPeopleId是评论人的ID，MyName是评论人的名字，Comment是评论人的评论内容
	public void AddComment(String Url, int PostId, int UserId,
			int CommentPeopleId, String CommentPeopleName, String Comment,
			int CircleId, String CircleName) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("postid", PostId);
			obj.put("userid", UserId);
			obj.put("commentpeopleid", CommentPeopleId);
			obj.put("commentpeoplename", CommentPeopleName);
			obj.put("comment", Comment);
			obj.put("circleid", CircleId);
			obj.put("circlename", CircleName);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				String responseStr = EntityUtils.toString(response.getEntity(),
						"utf8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Url:/deletePost
	// 供微博发表人删除微博用，postid是微博的主键
	public boolean DeletePost(String Url, int PostId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject obj = new JSONObject();
		try {
			obj.put("postid", PostId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				if(null!=responseStr&&"success".equals(responseStr)){
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// fetchPersonalMessage获取个人的收件箱//fetchMessage获取系统通知//fetchPostMessage获取曾经发送的消息
	public List<Messagebox> FetchMessagebox(String Url, int UserId) {

		List<Messagebox> list = new ArrayList<Messagebox>();
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject obj = new JSONObject();
		try {
			obj.put("userid", UserId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONArray array = object.getJSONArray("message");
				JSONObject tem = null;
				for (int i = 0; i < array.length(); i++) {
					Messagebox box = new Messagebox();
					tem = array.getJSONObject(i);
					box.setFromName(tem.getString("fromname"));
					box.setFromId(tem.getInt("fromid"));
					box.setContent(tem.getString("message"));
					box.setMessageType(tem.getInt("messagetype"));
					box.setTime(tem.getString("time"));
					list.add(box);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// Url:/getCirclePost
	// 获取群内成员发表的言论CircleId 是圈的ID
	public List<Post> GetCirclePost(String Url, int CircleId, int UserId,
			int minPostId, int flag) {

		List<Post> postlist = new ArrayList<Post>();
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject obj = new JSONObject();
		try {
			obj.put("circleid", CircleId);
			obj.put("minpostid", minPostId);
			obj.put("userid", UserId);
			obj.put("flag", flag);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("head");
				JSONArray array = object.getJSONArray("post");
				for (int i = 0; i < array.length(); i++) {
					Post temp = new Post();
					obj = array.getJSONObject(i);
					temp.setMessageType(obj.getInt("messagetype"));
					if (temp.getMessageType() == 1) {// 1为转发，0为原创微博
						temp.setHostId(obj.getInt("hostid"));// 存储被转发人的id
						// .out.println("hostid:" + post.getHostId());
						temp.setOriginalPostId(obj.getInt("originalpostid"));
						// .out.println("originalPostid:"
						// + post.getOriginalPostId());
						temp.setHostId(obj.getInt("hostid"));
						temp.setOriginalPostContent(obj
								.getString("originalpostcontent"));
						temp.setOriginalImage(obj.getString("originalimage"));

						temp.setOriginalUsername(obj
								.getString("originalusername"));
						temp.setOriginalLink(obj.getString("originallink"));
						if (IsPicture(temp.getOriginalLink()))
							temp.setOriginalDisplay(true);
						else
							temp.setOriginalDisplay(false);
					}
					temp.setLink(obj.getString("link"));
					if (IsPicture(temp.getLink()))
						temp.setDisplay(true);
					else
						temp.setDisplay(false);
					temp.setPostId(obj.getInt("postid"));
					temp.setImage(obj.getString("image"));
					// .out.println("postid:" + post.getPostId());
					temp.setPostContent(obj.getString("content"));
					// .out.println("content:" + post.getPostContent());
					temp.setPostTime(obj.getString("time"));
					// .out.println("time:" + post.getPostTime());
					temp.setRepostAmount(obj.getInt("repost"));
					// .out.println("repost:" + post.getRepostAmount());
					temp.setCommentsAmount(obj.getInt("commentamount"));
					temp.setCircleName(obj.getString("circlename"));
					// .out.println("circlename:" + post.getCircleName());
					// .out.println("commentamount:"
					// + post.getCommentsAmount());
					temp.setCircleId(obj.getInt("circleid"));
					postlist.add(temp);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return postlist;
	}

	// Url:/deleteCirclePeople
	// 供圈主删除圈员用，userid是删除对象的主id号
	public boolean DeleteCirclePeople(String Url, int CircleId, int UserId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject obj = new JSONObject();
		try {
			obj.put("circleid", CircleId);
			obj.put("userid", UserId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				if (null != responseStr && "success".equals(responseStr))
					return true;
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// Url:/getCirclePeopleInfor
	// 获取该组内成员的信息，返回时成员的昵称，粉丝数，关注数，微博发表的总数将会被填充
	public List<User> GetCirclePeopleInfor(String Url, int CircleId) {
		List<User> user = new ArrayList<User>();
		User temp = null;
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject obj = new JSONObject();
		try {
			obj.put("circleid", CircleId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("head");
				JSONArray json = object.getJSONArray("circlepeople");
				for (int i = 0; i < json.length(); i++) {
					obj = json.getJSONObject(i);
					temp = new User();
					temp.setName(obj.getString("username"));
					temp.setFan(obj.getInt("fan"));
					temp.setFollow(obj.getInt("follow"));
					temp.setPostAmount(obj.getInt("postamount"));
					temp.setId(obj.getInt("userid"));
					user.add(temp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	// Url:/getApplyPersonInfor,查看加圈人的信息
	public User GetApplyPersonInfor(String Url, int UserId) {// 圈主在获取申请信息后查看用户的个人信息，需要传入申请人的id
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		;
		JSONObject obj = new JSONObject();
		User user = new User();
		try {
			obj.put("userid", UserId);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("personinfor");

				user.setFan(object.getInt("fan"));
				user.setFollow(object.getInt("follow"));
				user.setPostAmount(object.getInt("postamount"));
				user.setName(object.getString("username"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	// Url:/joinCircle
	// 圈主处理请求的函数，hostid：圈主id，userid：申请人id。allow 布尔值，true
	// 同意，false反对，CircleId：圈子的id
	public void JoinCircle(String Url, int UserId, int HostId, int CircleId,
			boolean Allow) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", UserId);
			obj.put("hostid", HostId);
			obj.put("circleid", CircleId);
			obj.put("allow", Allow);
			pair.add(new BasicNameValuePair("json", obj.toString()));// 此处的json就是该对象的key值，在服务器端的response就需要再指定一次，这里不需要
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				String responseStr = EntityUtils.toString(response.getEntity(), "utf8");

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Url:/post
	// circleid为2，往关注对象发，1往周围圈子发
	public int SendPost(String url, int UserId, String content, int circleid,
			String CircleName, double Longitude, double Latitude) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject json = new JSONObject();
		try {
			json.put("content", content);
			json.put("id", UserId);
			json.put("circlename", CircleName);
			json.put("circleid", circleid);
			json.put("messagetype", 0);
			json.put("longitude", Longitude);
			json.put("latitude", Latitude);
			pair.add(new BasicNameValuePair("json", json.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			String responseStr = EntityUtils.toString(response.getEntity(),"utf8");
			return Integer.parseInt(responseStr);
		} catch (Exception e) {
			return -1;
		}
	}

	// Url:/applyCircle
	// UserId 申请人ID，HostId 圈主
	public boolean ApplyCircle(String Url, int UserId, int HostId,
			int CircleId, String CircleName, String UserName) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		Map map = new HashMap<String, Object>();
		map.put("hostid", HostId);
		map.put("circleid", CircleId);
		map.put("circlename", CircleName);
		map.put("username", UserName);
		map.put("userid", UserId);
		try {
			pair.add(new BasicNameValuePair("json", map.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity,"utf8");
				if (null != responseStr && "success".equals(responseStr))
					return true;
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// Url:/searchCircle,当无搜索结果时，返回null
	public List<Circle> SearchCircle(String url, String CircleName, int userid)// 按照圈类型搜索圈子,圈子名称，圈id，圈类型和圈总人数会被填充
	{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+url);
		List<Circle> circle = new ArrayList<Circle>();
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("circlename", CircleName);
			obj.put("userid", userid);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");// 此处可能有问题

				JSONArray array = object.getJSONArray("circle");
				if (array.length() == 0)
					return null;
				for (int i = 0; i < array.length(); i++) {
					Circle temp = new Circle();
					JSONObject tem = (JSONObject) array.opt(i);
					temp.setCircleId(tem.getInt("circleid"));
					temp.setCircleName(tem.getString("circlename"));
					temp.setCircleType(tem.getString("circletype"));
					temp.setAmount(tem.getInt("amount"));
					temp.setDescription(tem.getString("description"));
					temp.setUserId(tem.getInt("hostid"));
					temp.setFlag(tem.getInt("flag"));
					circle.add(temp);

				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return circle;

	}

	public boolean DeleteCircle(String Url, int CircleId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject json = new JSONObject();
		try {
			json.put("circleid", CircleId);
			pair.add(new BasicNameValuePair("json", json.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String responseStr = EntityUtils.toString(entity, "utf8");
			if (response.getStatusLine().getStatusCode() == 200) {
				if (null != responseStr && "success".equals(responseStr))
					return true;
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean ExitCircle(String Url, int userId, int circleId) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject json = new JSONObject();
		try {
			json.put("userid", userId);
			json.put("circleid", circleId);
			pair.add(new BasicNameValuePair("json", json.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String responseStr = EntityUtils.toString(entity, "utf8");
			if (response.getStatusLine().getStatusCode() == 200) {
				if (null != responseStr && "success".equals(responseStr))
					return true;
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * @param Url
	 *            :fetchJoinCircle
	 * @param UserId
	 *            :用户id
	 * @return
	 */
	public List<Circle> FetchJoinCircle(String Url, int UserId) {
		List<Circle> list = new ArrayList<Circle>();
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject json = new JSONObject();
		try {
			json.put("userid", UserId);
			pair.add(new BasicNameValuePair("json", json.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String responseStr = EntityUtils.toString(entity, "utf8");
			if (response.getStatusLine().getStatusCode() == 200) {
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("json");
				JSONObject tem = null;
				JSONArray array = object.getJSONArray("circle");
				for (int i = 0; i < array.length(); i++) {
					Circle circle = new Circle();
					tem = array.getJSONObject(i);
					circle.setCircleId(tem.getInt("circleid"));
					circle.setAmount(tem.getInt("amount"));
					circle.setCircleName(tem.getString("circlename"));
					circle.setDescription(tem.getString("description"));
					circle.setLevel(tem.getInt("level"));
					list.add(circle);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	// Url:/createCircle
	public boolean CreateCircle(String url, int UserId, String CircleName,
			String Description, String CircleType,int cid) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		JSONObject json = new JSONObject();
		try {
			json.put("id", UserId);
			json.put("description", Description);
			json.put("circlename", CircleName);
			json.put("circletype", CircleType);
			json.put("circleid", cid);
			pair.add(new BasicNameValuePair("json", json.toString()));
			post.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String responseStr = EntityUtils.toString(entity, "utf8");
			if (response.getStatusLine().getStatusCode() == 200) {
				if(null!=responseStr && "success".equals(responseStr)){
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public User login(String urlAddress, String mail, String password) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_BASE+urlAddress);
		List<NameValuePair> Pair = new ArrayList<NameValuePair>();
		JSONObject ob = new JSONObject();
		try {
			ob.put("mail", mail);
			ob.put("password", password);

			Pair.add(new BasicNameValuePair("json", ob.toString()));
			post.setEntity(new UrlEncodedFormEntity(Pair, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			String responseStr = EntityUtils.toString(response.getEntity(),"utf8");
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity out = response.getEntity();
				if (out != null) {
					if (responseStr == null) {
					} else {
						JSONObject obj = new JSONObject(responseStr)
								.getJSONObject("json");
						if (obj.getInt("result") == 1) {
							User user = new User();
							user.setId(obj.getInt("userid"));
							user.setImage(obj.getString("image"));
							user.setName(obj.getString("name"));
							user.setFan(obj.getInt("fan"));
							user.setFollow(obj.getInt("follow"));
							user.setPostAmount(obj.getInt("postamount"));
							return user;
						}

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public long getLength() {
		return length;
	}

	public void setLength(long length) {
		this.length = length;
	}

	public String getFileType() {
		return fileType;
	}

	public void setFileType(String fileType) {
		this.fileType = fileType;
	}

	public List<User> SearchPeople(String Url, String Name, int userId) {
		List<User> list = new ArrayList<User>();
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(URL_BASE+Url);
		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		try {
			JSONObject obj = new JSONObject();
			obj.put("userid", userId);
			obj.put("name", Name);
			pair.add(new BasicNameValuePair("json", obj.toString()));
			request.setEntity(new UrlEncodedFormEntity(pair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String responseStr = EntityUtils.toString(entity, "utf8");
				JSONObject object = new JSONObject(responseStr)
						.getJSONObject("array");
				JSONObject tem = null;
				JSONArray array = object.getJSONArray("people");
				for (int i = 0; i < array.length(); i++) {
					tem = array.getJSONObject(i);
					User temp = new User();
					temp.setName(tem.getString("name"));
					temp.setId(tem.getInt("userid"));
					temp.setFan(tem.getInt("fan"));
					temp.setFlag(tem.getInt("flag"));
					temp.setImage(tem.getString("image"));
					temp.setPostAmount(tem.getInt("postamount"));
					list.add(temp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;

	}
}
